﻿using Hardcodet.Wpf.TaskbarNotification;
using Microsoft.Win32;
using System.Configuration;
using System.Data;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace PlayNote
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            //TimeHelper.GetHolidayByYearAsync1();
            //首先注册开始和退出事件
            this.Startup += new StartupEventHandler(App_Startup);
            this.Exit += new ExitEventHandler(App_Exit);

            void App_Startup(object sender, StartupEventArgs e)
            {
                //UI线程未捕获异常处理事件
                this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
                //Task线程内未捕获异常处理事件
                TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
                //非UI线程未捕获异常处理事件
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            }

            void App_Exit(object sender, ExitEventArgs e)
            {
                //程序退出时需要处理的业务
                _keyboardHook.UnHook();
            }


            void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
            {
                try
                {
                    e.Handled = true; //把 Handled 属性设为true，表示此异常已处理，程序可以继续运行，不会强制退出      
                    MessageBox.Show("UI线程异常:" + e.Exception.Message);
                }
                catch (Exception ex)
                {
                    //此时程序出现严重异常，将强制结束退出
                    MessageBox.Show("UI线程发生致命错误！");
                }

            }

            void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                StringBuilder sbEx = new StringBuilder();
                if (e.IsTerminating)
                {
                    sbEx.Append("非UI线程发生致命错误");
                }
                sbEx.Append("非UI线程异常：");
                if (e.ExceptionObject is Exception)
                {
                    sbEx.Append(((Exception)e.ExceptionObject).Message);
                }
                else
                {
                    sbEx.Append(e.ExceptionObject);
                }
                MessageBox.Show(sbEx.ToString());
            }

            void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
            {
                //task线程内未处理捕获
                MessageBox.Show("Task线程异常：" + e.Exception.Message);
                e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
            }
        }
        private TaskbarIcon _taskbar;
        System.Threading.Mutex mutex;
        KeyboardHook _keyboardHook;
        protected override void OnStartup(StartupEventArgs e)
        {
            _taskbar = (TaskbarIcon)FindResource("Taskbar");
            _taskbar.ContextMenu.Width = 120;
            base.OnStartup(e);
            setSingleStart();
            setAutoStart();
            _keyboardHook = new KeyboardHook();
            _keyboardHook.SetHook();
            _keyboardHook.SetOnKeyDownEvent(Win32_Keydown);
            _keyboardHook.SetOnKeyUpEvent(Win32_Keyon);

        }
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.Shutdown();
        }
        /// <summary>
        /// 设置单例启动
        /// </summary>
        void setSingleStart()
        {
            var name = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name;
            #region 单例启动
            bool ret;
            mutex = new System.Threading.Mutex(true, name, out ret);//这里填写程序名称
            if (!ret)
            {
                _taskbar.Dispose();
                Environment.Exit(0);
            }

            #endregion
        }
        /// <summary>
        /// 设置开机自启
        /// </summary>
        void setAutoStart()
        {
            #region 设置开机自启
            string strName = AppDomain.CurrentDomain.BaseDirectory + System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ".exe";//获取要自动运行的应用程序名
            if (!System.IO.File.Exists(strName))//判断要自动运行的应用程序文件是否存在
                return;
            string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);//获取应用程序文件名，不包括路径
            RegistryKey registry = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//检索指定的子项
            if (registry == null)//若指定的子项不存在
                registry = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//则创建指定的子项
            registry.SetValue(strnewName, strName);//设置该子项的新的“键值对”
            #endregion
        }

        bool lctrlIsPress = false;
        bool rctrlIsPress = false;
        bool lshiftIsPress = false;
        bool rshiftIsPress = false;
        bool laltIsPress = false;
        bool raltIsPress = false;
        bool lwinIsPress = false;
        bool rwinIsPress = false;
        private void Win32_Keydown(Key key)
        {
            switch (key)
            {
                case Key.LeftCtrl:
                    {
                        //ExitFullscreen();
                        lctrlIsPress = true;
                    }
                    break;
                case Key.RightCtrl:
                    {
                        //ExitFullscreen();
                        rctrlIsPress = true;
                    }
                    break;
                case Key.LeftShift:
                    {
                        //ExitFullscreen();
                        lshiftIsPress = true;
                    }
                    break;
                case Key.RightShift:
                    {
                        //ExitFullscreen();
                        rshiftIsPress = true;
                    }
                    break;


                case Key.LWin:
                    {
                        //ExitFullscreen();
                        lwinIsPress = true;
                    }
                    break;
                case Key.RWin:
                    {
                        //ExitFullscreen();
                        rwinIsPress = true;
                    }
                    break;

                case Key.LeftAlt:
                    {
                        //ExitFullscreen();
                        laltIsPress = true;
                    }
                    break;
                case Key.RightAlt:
                    {
                        //ExitFullscreen();
                        raltIsPress = true;
                    }
                    break;
            }
        }

        private void Win32_Keyon(Key key) 
        {

            switch (key)
            {
                case Key.LeftCtrl:
                    {
                        //ExitFullscreen();
                        lctrlIsPress = false;
                    }
                    break;
                case Key.RightCtrl:
                    {
                        //ExitFullscreen();
                        rctrlIsPress = false;
                    }
                    break;
                case Key.LeftShift:
                    {
                        //ExitFullscreen();
                        lshiftIsPress = false;
                    }
                    break;
                case Key.RightShift:
                    {
                        //ExitFullscreen();
                        rshiftIsPress = false;
                    }
                    break;


                case Key.LWin:
                    {
                        //ExitFullscreen();
                        lwinIsPress = false;
                    }
                    break;
                case Key.RWin:
                    {
                        //ExitFullscreen();
                        rwinIsPress = false;
                    }
                    break;

                case Key.LeftAlt:
                    {
                        //ExitFullscreen();
                        laltIsPress = false;
                    }
                    break;
                case Key.RightAlt:
                    {
                        //ExitFullscreen();
                        raltIsPress = false;
                    }
                    break;

                case Key.Q:
                    {
                        if (lctrlIsPress||rctrlIsPress)
                        {
                            MessageBox.Show("成功");
                        }
                        break;
                    }
            }
        }
    }

}
